import { useEffect, useState } from "react";

import {
  Form,
  Button,
  DatePicker,
  Checkbox,
  Radio,
  Modal,
  Divider,
} from "antd";

import { SaveOutlined, PrinterOutlined } from "@ant-design/icons";

import html2pdf from "html2pdf.js";

import locale from "antd/es/date-picker/locale/zh_CN";

import "dayjs/locale/zh-cn";
import dayjs from "dayjs";

import styles from "./index.module.scss";
import "./index.global.scss";
import { formaData, req } from "@/common/methods";

import LoadingComponent from "@/components/Loading/index.tsx";

const Accounts = () => {
  const [month, setMonth] = useState(
    (() => {
      const date = new Date();
      return `${date.getFullYear()}-${("" + (date.getMonth() + 1)).padStart(
        2,
        "0"
      )}`;
    })()
  );
  const [expoData, setExpoData] = useState([]);
  const [formValues, setFormValues] = useState({
    category: -1,
    month: dayjs(month),
    range: 21,
    field: ["after_count", "empl", "remark"],
    sort: 3,
    paper_orientation: 1,
    time_format: 2,
    show_tabulation_time: true,
  });
  const [loading, setLoading] = useState(true);
  const [dataCategory, setDataCategory] = useState([]);
  const [dataGoods, setDataGoods] = useState({});
  const [depart, setDepart] = useState([]);
  const [suppliers, setSuppliers] = useState([]);
  const [generateTime, setGenerateTime] = useState(new Date());
  const [isOpenTab, setIsOpenTab] = useState(false);
  const [printCount, setPrintCount] = useState(0);
  const [generateLoading, setGenerateLoading] = useState(false);

  const savePDF = () => {
    try {
      if (!document.querySelector("[data-generate-account]")) {
        throw "元素不存在，您可能需要重新生成报表";
      }
      html2pdf()
        .from(document.querySelector("[data-generate-account]")) //#account-package
        .set({
          margin: 3,
          filename: `${
            document.querySelector("[data-file-name-content]")?.innerHTML ||
            "导出文件"
          }.pdf`,
          image: { type: "jpeg", quality: 0.98 },
          html2canvas: { scale: 2 },
          jsPDF: {
            unit: "mm",
            format: "a4",
            orientation:
              formValues.paper_orientation === 1 ? "landscape" : "portrait",
          },
        })

        .save();
    } catch (e) {
      Modal.error({
        title: "系统出错",
        content: <>无法保存此文件：{"" + e}</>,
      });
    }
    //html2pdf().from(document.querySelector("#ppddff")).save();
  };
  const printR = () => {
    try {
      const targetElement = document.querySelector(
        "div[data-generate-account]"
      );
      const targetElementParent = targetElement?.parentElement;
      if (!targetElement) {
        throw "目标元素不存在";
      }
      document.body.childNodes.forEach((item: ChildNode) => {
        if (item && (item as any)?.tagName && (item as any)?.style) {
          if ((item as any)?.tagName === "DIV") {
            (item as any).style.display = "none";
          }
        }
      });
      document.body.appendChild(targetElement);
      window.print();
      document.body.removeChild(targetElement);
      targetElementParent?.appendChild(targetElement);
      document.body.childNodes.forEach((item) => {
        if (item && (item as any)?.tagName && (item as any)?.style) {
          if ((item as any)?.tagName === "DIV") {
            (item as any).style.display = "block";
          }
        }
      });
      setPrintCount(printCount + 1);
      //onFinish(formValues);
    } catch (e) {
      Modal.error({
        title: "系统出错",
        content: <>无法打印报表：{"" + e}</>,
      });
    }
  };

  const fetchBaseData = () => {
    req("/api/goods/easy_get")
      .then((data: any) => {
        setDataGoods(data as any);
        return req("/api/category/get");
      })
      .then((data: any) => {
        setDataCategory(data as any);
        return req("/api/depart/get");
      })
      .then((data: any) => {
        setDepart(data);
        console.log(data);
        return req("/api/suppliers/get");
      })
      .then((data: any) => {
        setSuppliers(data);
        setLoading(false);
      })
      .catch(() => {});
  };
  useEffect(() => {
    fetchBaseData();
  }, []);

  const onFinish = (values: any) => {
    //console.log(values);
    setGenerateLoading(true);
    req(
      "/api/generate_con",
      {
        ...values,
        month: ((): string => {
          const date = values.month.$d;
          return `${date.getFullYear()}-${("" + (date.getMonth() + 1)).padStart(
            2,
            "0"
          )}`;
        })(),
      },
      "post"
    )
      .then((data: any) => {
        setExpoData(data);
        setFormValues(values);
        setGenerateTime(new Date());
        setIsOpenTab(true);
        setGenerateLoading(false);
      })
      .catch((error) => {
        Modal.error({
          title: "系统出错",
          content: <>无法获取数据，{"" + error}</>,
          onOk() {
            setGenerateLoading(false);
          },
        });
      });
  };
  return (
    <>
      {/* <div>月份（某年某月）</div>
      <div>表格类型（领用、进货、退库、退货）</div>
      <div>按什么排序（发生时间或创建时间）</div>
      <div>需要字段（）</div>
      <div>打印时附上打印时间（是或否）</div>
      <div>报表生成排版（横版或竖版）</div>
      <div>按什么排序？领用时间还是部门</div>
      <div>生成报表</div> */}
      {loading ? (
        <>请稍候……</>
      ) : (
        <Form
          name="accounts_generate"
          layout="inline"
          className={styles["accounts-form"]}
          initialValues={formValues}
          onFinish={onFinish}
          onFinishFailed={() =>
            Modal.error({
              title: "无法生成报表",
              content: <>请检查您的填写是否正确</>,
            })
          }
          disabled={generateLoading}
        >
          <Form.Item
            name="month"
            label="月份"
            rules={[{ required: true, message: "请选择月份" }]}
          >
            <DatePicker
              picker="month"
              locale={locale}
              onChange={(date, dateString) => {
                date;
                setMonth(dateString);
              }}
            />
          </Form.Item>
          <Form.Item name="category" label="分类" required>
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              {dataCategory.map((item: any) => (
                <Radio key={item.id} value={item.id}>
                  {item.name}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>
          <Form.Item name="range" label="范围" required>
            {/* <Checkbox.Group
            options={[
              { label: "进货", value: 10 },
              { label: "退货", value: 11 },
              { label: "退库", value: 20 },
              { label: "领用", value: 21 },
              { label: "盘盈", value: 30 },
              { label: "盘亏", value: 31 },
            ]}
          /> */}
            <Radio.Group>
              <Radio value={10}>进货</Radio>
              <Radio value={11}>退货</Radio>
              <Radio value={20}>退库</Radio>
              <Radio value={21}>领用</Radio>
              <Radio value={30}>盘盈</Radio>
              <Radio value={31}>盘亏</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="field" label="字段">
            <Checkbox.Group
              options={[
                { label: "结余", value: "after_count" },
                { label: "申请人/经手人", value: "requ" },
                { label: "领用人/交回人/进货人/退货人", value: "empl" },
                { label: "单号", value: "doc_id" },
                { label: "备注", value: "remark" },
              ]}
            />
          </Form.Item>
          <Form.Item name="sort" label="排序" required>
            <Radio.Group>
              <Radio value={1}>时间正序</Radio>
              <Radio value={2}>时间倒序</Radio>
              <Radio value={3}>部门/供货商正序</Radio>
              <Radio value={4}>部门/供货商倒序</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="paper_orientation" label="纸张方向" required>
            <Radio.Group>
              <Radio value={1}>横向</Radio>
              <Radio value={2}>纵向</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="time_format" label="时间格式" required>
            <Radio.Group>
              <Radio value={1}>显示日期和时间</Radio>
              <Radio value={2}>只显示日期</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="show_tabulation_time" label="制表时间" required>
            <Radio.Group>
              <Radio value={true}>显示</Radio>
              <Radio value={false}>隐藏</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={generateLoading}
              onClick={() => {
                // html2pdf()
                //   .set({
                //     margin: 1,
                //     filename: "myfile.pdf",
                //     image: { type: "jpeg", quality: 0.98 },
                //     html2canvas: { scale: 2 },
                //     jsPDF: {
                //       unit: "mm",
                //       format: "a4",
                //       orientation: "landscape",
                //     },
                //   })
                //   .from(document.querySelector("#account-package"))
                //   .save();
                // //html2pdf().from(document.querySelector("#ppddff")).save();
              }}
            >
              生成报表
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="default"
              danger
              onClick={() => {
                try {
                  setExpoData([]);
                  setIsOpenTab(false);
                } catch (e) {
                  alert("出错");
                }
                //console.log("重置报表");
                //html2pdf().from(document.querySelector("#ppddff")).save();
              }}
            >
              关闭报表
            </Button>
          </Form.Item>
        </Form>
      )}
      {generateLoading && (
        <>
          <LoadingComponent text="系统正在生成报表" />
        </>
      )}
      {isOpenTab && (
        <>
          <div className={styles["toolbar"]}>
            <div>{``}</div>
            <div className={styles["btn-area"]}>
              <button className={styles["xp-btn"]} onClick={savePDF}>
                <SaveOutlined />
                {` `}
                保存为文档
              </button>
              <button className={styles["xp-btn"]} onClick={printR}>
                <PrinterOutlined />
                {` `}打印报表
              </button>
            </div>
          </div>
        </>
      )}
      {isOpenTab && (
        <div id="account-package" className="account-package" key={printCount}>
          <div data-generate-account>
            {isOpenTab ? (
              <>
                <h1 data-file-name-content>{`${(() => {
                  const find = dataCategory.find(
                    (item: any) => item?.id === formValues.category
                  );
                  if (!find || !(find as any)?.name) {
                    return "物品";
                  } else {
                    let name = "" + ((find as any)?.name || "物品");
                    if (
                      !["物品", "用品"].includes(
                        name.substring(name.length - 2, name.length)
                      )
                    ) {
                      name = name + "用品";
                    }
                    return name;
                  }
                })()}${
                  {
                    10: "进货",
                    11: "退货",
                    20: "退库",
                    21: "领用",
                    30: "盘盈",
                    31: "盘亏",
                  }[formValues.range] || "变动"
                }详情(${(() => {
                  if (
                    typeof formValues.month === "undefined" ||
                    typeof (formValues.month as any).$d === "undefined"
                  ) {
                    return "未知月份";
                  }
                  const date = (formValues.month as any).$d;
                  return `${date.getFullYear()}年${date.getMonth() + 1}月`;
                })()})`}</h1>
                <table>
                  <thead>
                    <tr>
                      <th className="th-method">
                        {formValues.range % 10 === 1 ? "出库" : "入库"}方式
                      </th>
                      <th className="th-goods-name">物品名称</th>
                      <th className="th-specs">规格</th>
                      <th className="th-units">单位</th>
                      <th className="th-change-count">数量</th>
                      {formValues.field.find(
                        (item) => item === "after_count"
                      ) && <th className="th-after-count">结余</th>}
                      <th className="th-depart">
                        {["-", "供货商", "部门", "-"][
                          Math.floor(formValues.range / 10)
                        ] || "部门"}
                      </th>
                      {formValues.field.find((item) => item === "requ") && (
                        <th className="th-requ">申请人</th>
                      )}
                      {formValues.field.find((item) => item === "empl") && (
                        <th className="th-empl">领用人</th>
                      )}
                      <th
                        className={[
                          "th-time",
                          formValues.time_format === 2
                            ? "time-column-short"
                            : "time-column-long",
                        ].join(" ")}
                      >
                        时间
                      </th>
                      {formValues.field.find((item) => item === "doc_id") && (
                        <th className="th-goods-id">单号</th>
                      )}
                      {formValues.field.find((item) => item === "remark") && (
                        <th className="th-remark">备注</th>
                      )}
                    </tr>
                  </thead>
                  <tbody>
                    {expoData.map((item: any) => (
                      <tr key={item.id}>
                        <td>
                          {
                            {
                              10: "进货",
                              11: "退货",
                              20: "退库",
                              21: "领用",
                              30: "盘盈",
                              31: "盘亏",
                            }[formValues.range]
                          }
                        </td>
                        <td>
                          {typeof (dataGoods as any)[item.goods_id] !==
                          "undefined" ? (
                            (dataGoods as any)[item.goods_id]?.name
                          ) : (
                            <span style={{ color: "red" }}>
                              已删除物品[{item.goods_id}]
                            </span>
                          )}
                        </td>
                        <td>
                          {typeof (dataGoods as any)[item.goods_id] !==
                          "undefined" ? (
                            (dataGoods as any)[item.goods_id]?.specs
                          ) : (
                            <span style={{ color: "red" }}>-</span>
                          )}
                        </td>
                        <td>
                          {typeof (dataGoods as any)[item.goods_id] !==
                          "undefined" ? (
                            (dataGoods as any)[item.goods_id]?.unit
                          ) : (
                            <span style={{ color: "red" }}>-</span>
                          )}
                        </td>
                        <td>{Math.abs(item.change_count)}</td>
                        {formValues.field.find(
                          (item) => item === "after_count"
                        ) && <td>{item.after_count}</td>}
                        <td>
                          {Math.floor(formValues.range / 10) === 1
                            ? (
                                suppliers.find(
                                  (item1: any) => item1.id == item.depart
                                ) as any
                              )?.name || `未知[${item.depart}]`
                            : (
                                depart.find(
                                  (item1: any) => item1.id == item.depart
                                ) as any
                              )?.name || `未知[${item.depart}]`}
                        </td>
                        {formValues.field.find((item) => item === "requ") && (
                          <td>{item.requ}</td>
                        )}
                        {formValues.field.find((item) => item === "empl") && (
                          <td>{item.empl}</td>
                        )}
                        <td>
                          {formValues.time_format === 1
                            ? item.time
                            : (() => {
                                const date = new Date(item.time);
                                return `${date.getFullYear()}年${
                                  date.getMonth() + 1
                                }月${date.getDate()}日`;
                              })()}
                        </td>
                        {formValues.field.find((item) => item === "doc_id") && (
                          <td>{item.doc_id}</td>
                        )}
                        {formValues.field.find((item) => item === "remark") && (
                          <td>{item.remark}</td>
                        )}
                      </tr>
                    ))}
                  </tbody>
                </table>
                {formValues.show_tabulation_time && (
                  <Divider orientation="right" plain>
                    <div style={{ opacity: 0.5 }}>
                      制表时间：<span>{formaData(generateTime)}</span>
                    </div>
                  </Divider>
                )}
              </>
            ) : (
              <>请先生成报表</>
            )}
          </div>
        </div>
      )}
    </>
  );
};

export default Accounts;
